package com.shhm.common.utils;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.lang.reflect.Field;

/**
 * @author JackZ
 * @version 1.0
 * @description: MybatisPlus工具类
 * @date 2025/8/12 下午2:30
 */
public class MybatisPlusUtil {
    /**
     * 根据实体对象中非空字段，自动构建 like 查询条件
     * @param entity 实体对象
     * @param <T> 实体类型
     * @return LambdaQueryWrapper<T>
     */
    public static <T> QueryWrapper<T> buildSearchQueryWrapper(T entity) {
        Class<T> clazz = (Class<T>) entity.getClass();
        QueryWrapper<T> wrapper = new QueryWrapper<>();

        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object value = field.get(entity);


                if (
                        value == null
                        || (value instanceof String && ((String) value).trim().isEmpty())
                        || (value instanceof Long && ((Long) value)==0)
                        || (value instanceof Integer && ((Integer) value)==0)
                        || field.getName().equals("serialVersionUID")
                        || field.isAnnotationPresent(TableId.class)
                )
                {
                    continue;
                }

                String columnName = camelToUnderline(field.getName());
                if (value instanceof String) wrapper.like(columnName, value);
                else if (value instanceof Integer||value instanceof Long) wrapper.eq(columnName,value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return wrapper;
    }

    /**
     * 驼峰命名转下划线命名（userName -> user_name）
     * @param camelCaseName 驼峰名
     * @return 下划线命名
     */
    private static String camelToUnderline(String camelCaseName) {
        if (camelCaseName == null || camelCaseName.isEmpty()) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        result.append(camelCaseName.substring(0, 1).toLowerCase());
        for (int i = 1; i < camelCaseName.length(); i++) {
            char ch = camelCaseName.charAt(i);
            if (Character.isUpperCase(ch)) {
                result.append("_").append(Character.toLowerCase(ch));
            } else {
                result.append(ch);
            }
        }
        return result.toString();
    }
}
